package com.seo.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seo.pojo.ReturnBody;

import lombok.extern.slf4j.Slf4j;

/**
 * 关键词指数相关接口访问
 * 
 * @author Administrator
 * @version 2017.12.01 11:40
 */
@Slf4j
public final class KeyWordsIndex {
	private KeyWordsIndex() {
	};

	/**
	 * 获取关键词指数
	 * 
	 * @param keyWord
	 *            关键词
	 * @param key
	 *            统一key
	 * @param params
	 *            搜索引擎接口
	 * @return List<Map<String,Object>>
	 */
	public static List<Map<String, Object>> getKeyWordsIndex(List<String> keyWords, String key, List<String> params) {
		log.info("获取关键词指数开始");
		List<Map<String, Object>> index = new ArrayList<>();
		if (keyWords.size() > 0 && !StringUtils.isEmpty(key) && params != null && params.size() > 0) {
			try {
				for (int i = 0; i < keyWords.size(); i++) {
					String keyWord = keyWords.get(i).trim();
					Map<String, Object> indexs = new HashMap<String, Object>();
					indexs.put("keyWord", keyWord);
					for (String url : params) {
						String inde = "0";
						StringBuffer urls = new StringBuffer();
						if (url != null) {
							urls.append(url + "?key=").append(key).append("&keyword=").append(keyWord);
							log.info("获取关键词指数的---url{}", urls.toString());
							String res = HttpClientManagerT.getDatas(urls.toString());
							log.info("获取关键词指数的---结果{}", res);
							if (StringUtils.isEmpty(res)) {
								log.error("获取关键词指数失败!");
								return null;
							}
							JSONObject tokenjson = JSONObject.parseObject(res);
							String param = url.substring((url.lastIndexOf("/") + 1), url.length());
							if ("SmIndex".equals(param)) {
								if (tokenjson.get("StateCode").equals(1)) {
									if(!"该关键词暂无指数！".equals(tokenjson.get("Reason"))){
										JSONObject json = (JSONObject) tokenjson.get("Result");
										inde = json.get("Sm") + "";
										if(inde.contains(",")) {
											String[] split = inde.split(",");
											inde = split[split.length-1];
										}
									}
									indexs.put("shenma", inde);
								}
							} else if ("SoIndex".equals(param)) {
								if (tokenjson.get("StateCode").equals(1)) {
									if(!"该关键词暂无指数！".equals(tokenjson.get("Reason"))){
										JSONObject json = (JSONObject) tokenjson.get("Result");
										inde = json.get("SoPc") + "";
										if(inde.contains(",")) {
											String[] split = inde.split(",");
											inde = split[split.length-1];
										}
									}
									indexs.put("so", inde);
								}
							} else if ("BaiduIndex".equals(param)) {
								if (tokenjson.get("StateCode").equals(1)) {
									if(!"该关键词暂无指数！".equals(tokenjson.get("Reason"))){
										JSONObject json = (JSONObject) tokenjson.get("Result");
										inde = json.get("BaiduPc") + "";
										if(inde.contains(",")) {
											String[] split = inde.split(",");
											inde = split[split.length-1];
										}
										indexs.put("BaiduPc", inde);
										inde = json.get("BaiduMobile") + "";
										if(inde.contains(",")) {
											String[] split = inde.split(",");
											inde = split[split.length-1];
										}
									}
									indexs.put("BaiduMobile", inde);
								}
							} else if ("SogouIndex".equals(param)) {
								if (tokenjson.get("StateCode").equals(1)) {
									if(!"该关键词暂无指数！".equals(tokenjson.get("Reason"))){
										JSONObject json = (JSONObject) tokenjson.get("Result");
										inde = json.get("SogouPc") + "";
										if(inde.contains(",")) {
											String[] split = inde.split(",");
											inde = split[split.length - 1];
										}
										indexs.put("SogouPc", inde);
										inde = json.get("SogouMobile") + "";
										if(inde.contains(",")) {
											String[] split = inde.split(",");
											inde = split[split.length - 1];
										}
										indexs.put("SogouMobile", inde);
									} else {
										indexs.put("SogouPc", inde);
										indexs.put("SogouMobile", inde);
									}
								}
							}
						} else {
							log.error("获取关键词指数失败!");
							return null;
						}
					}
					index.add(indexs);
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("获取关键词指数异常！{}", e);
				return null;
			}
		} else {
			log.error("获取关键词指数参数有误---keyWord={}, key={}, params={}", keyWords, key, params);
		}
		log.info("获取关键词指数结束");
		return index;
	}
	
	/**
	 * 获取关键词指数
	 * 
	 * @param keyWord
	 *            关键词
	 * @param key
	 *            统一key
	 * @param engineCode
	 *            引擎接口
	 * @return List<Map<String,Object>>
	 */
	public static String getKeyWordsInde(String keyWord, String key, String url) {
		log.info("获取关键词指数开始");
		String index = "0";
		if (!StringUtils.isEmpty(keyWord) && !StringUtils.isEmpty(key) && !StringUtils.isEmpty(url)) {
			try {
				if("01".equals(url) || "02".equals(url)) {
					url = "http://apidata.chinaz.com/CallAPI/BaiduIndex";
				} else if("03".equals(url) || "04".equals(url)) {
					url = "http://apidata.chinaz.com/CallAPI/SoIndex";
				} else if("05".equals(url)) {
					url = "http://apidata.chinaz.com/CallAPI/SmIndex";
				} else if("06".equals(url) || "07".equals(url)) {
					url = "http://apidata.chinaz.com/CallAPI/SogouIndex";
				}
				keyWord = keyWord.trim();
			    StringBuffer urls = new StringBuffer();
				urls.append(url + "?key=").append(key).append("&keyword=").append(keyWord);
				log.info("获取关键词指数的---url{}", urls.toString());
				String res = HttpClientManagerT.getDatas(urls.toString());
				log.info("获取关键词指数的---结果{}", res);
				if (StringUtils.isEmpty(res)) {
					log.error("获取关键词指数失败!");
					return null;
				}
				JSONObject tokenjson = JSONObject.parseObject(res);
				String param = url.substring((url.lastIndexOf("/") + 1), url.length());
				if ("SmIndex".equals(param)) {
					if (tokenjson.get("StateCode").equals(1)) {
						if(!"该关键词暂无指数！".equals(tokenjson.get("Reason"))){
							JSONObject json = (JSONObject) tokenjson.get("Result");
							index = json.get("Sm") + "";
							if(index.contains(",")) {
								String[] split = index.split(",");
								index = split[split.length-1];
							} 
						} else {
							return index;
						}
					}
				} else if ("SoIndex".equals(param)) {
					if (tokenjson.get("StateCode").equals(1)) {
						if(!"该关键词暂无指数！".equals(tokenjson.get("Reason"))){
							JSONObject json = (JSONObject) tokenjson.get("Result");
							index = json.get("SoPc") + "";
							if(index.contains(",")) {
								String[] split = index.split(",");
								index = split[split.length-1];
							}
						} else {
							return index;
						}
					}
				} else if ("BaiduIndex".equals(param)) {
					if (tokenjson.get("StateCode").equals(1)) {
						if(!"该关键词暂无指数！".equals(tokenjson.get("Reason"))){
							JSONObject json = (JSONObject) tokenjson.get("Result");
							if("01".equals(url)) {
								index = json.get("BaiduPc") + "";
							} else {
								index = json.get("BaiduMobile") + "";
							}
							if(index.contains(",")) {
								String[] split = index.split(",");
								index = split[split.length-1];
							}
						} else {
							return index;
						}
					}
				} else if ("SogouIndex".equals(param)) {
					if (tokenjson.get("StateCode").equals(1)) {
						if(!"该关键词暂无指数！".equals(tokenjson.get("Reason"))){
							JSONObject json = (JSONObject) tokenjson.get("Result");
							if("06".equals(url)) {
								index = json.get("SogouPc") + "";
							} else {
								index = json.get("SogouMobile") + "";
							}
							if(index.contains(",")) {
								String[] split = index.split(",");
								index = split[split.length-1];
							}
						} else {
							return index;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("获取关键词指数异常！{}", e);
				return "0";
			}
		} else {
			log.error("获取关键词指数参数有误---keyWord={}, key={}", keyWord, key);
		}
		log.info("获取关键词指数结束");
		return index;
	}

	/**
	 * 获取关键词排名
	 * 
	 * @param keyWord
	 *            关键词
	 * @param domain
	 *            域名
	 * @param engineCode
	 * @return ReturnBody
	 */
	public static ReturnBody getKeyWordsRanking(String keyword, String domain, String engineCode) {
		log.info("获取关键词排名开始");
		ReturnBody rb = ReturnBody.init();
		String url = "";
		StringBuffer urls = new StringBuffer();
		String key = "23fe53c6570e4da1bf37a7f23155e63b";
		try {
			if (StringUtils.isEmpty(keyword) || StringUtils.isEmpty(domain) || StringUtils.isEmpty(engineCode)) {
				log.error("缺少参数!");
				return rb.error("缺少参数!");
			}
			if ("01".equals(engineCode)) {
				url = "http://apidata.chinaz.com/CallAPI/BaiduPcRanking";
			} else if ("02".equals(engineCode)) {
				url = "http://apidata.chinaz.com/CallAPI/BaiduMobileRanking";
			} else if ("03".equals(engineCode)) {
				url = "http://apidata.chinaz.com/CallAPI/SoPcRanking";
			} else if ("04".equals(engineCode)) {
				url = "http://apidata.chinaz.com/CallAPI/SoMobileRanking";
			} else if ("05".equals(engineCode)) {
				url = "http://apidata.chinaz.com/CallAPI/SmRanking";
			} else if ("06".equals(engineCode)) {
				url = "http://apidata.chinaz.com/CallAPI/SogouPcRanking";
			} else if ("07".equals(engineCode)) {
				url = "http://apidata.chinaz.com/CallAPI/SogouMobileRanking";
			}
			urls.append(url + "?key=").append(key).append("&domainName=").append(domain).append("&keyword=" + keyword);
			log.info("获取关键词排名---url{}", urls.toString());
			String res = HttpClientManagerT.getData(urls.toString());
			log.info("获取关键词排名---结果{}", res);
			if (StringUtils.isEmpty(res)) {
				rb.put("ranking", "10000");
			}
			JSONObject tokenjson = JSONObject.parseObject(res);
			if (tokenjson == null) {
				rb.put("ranking", "10000");
			}
			if (tokenjson.get("StateCode").equals(1)) {
				JSONObject result = (JSONObject) tokenjson.get("Result");
				JSONArray ranks = result.getJSONArray("Ranks");
				if (ranks != null && ranks.size() > 0) {
					JSONObject rank = ranks.getJSONObject(0);
					String rankStr = rank.getString("RankStr");
					String[] ranking = rankStr.split("-");
					Integer rank1 = Integer.parseInt(ranking[0]);
					Integer rank2 = Integer.parseInt(ranking[1]);
					rb.put("ranking", String.valueOf((rank1 - 1) * 10 + rank2));
				} else {
					rb.put("ranking", "10000");
				}

			} else {
				rb.put("ranking", "10000");
			}
		} catch (Exception e) {
			rb.put("ranking", "10000");
			return rb.success();
		}
		log.info("获取关键词排名结束");
		return rb.success();
	}

	public static void main(String[] args) {
		/*
		 * List<String> indexs = new ArrayList<String>(); String
		 * key="23fe53c6570e4da1bf37a7f23155e63b";
		 * indexs.add("http://apidata.chinaz.com/CallAPI/SmIndex");
		 * indexs.add("http://apidata.chinaz.com/CallAPI/SoIndex");
		 * indexs.add("http://apidata.chinaz.com/CallAPI/SogouIndex");
		 * indexs.add("http://apidata.chinaz.com/CallAPI/BaiduIndex"); String[]
		 * keyWord={"苹果","老虎机"}; List<Map<String, Object>> keyWordsIndex =
		 * getKeyWordsIndex(keyWord, key, indexs);
		 * System.out.println(keyWordsIndex);
		 */
		ReturnBody rb = getKeyWordsRanking("橡胶制品定做", "hbjymf.com", "01");
		System.out.println(rb.get("ranking"));
		
	}

}
